<template>
  <div class="createPost-container">
    <el-form class="form-container" :model="postForm" :rules="rules" ref="postForm">

      <sticky :className="'sub-navbar '+postForm.status">
          <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm()">发布
          </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="110px" label="栏目资讯：" class="postInfo-container-item" prop="brand" >
                      <el-cascader
                         change-on-select  placeholder="请选择" expand-trigger="click"
                        :options="sections"
                        v-model="sectionIds"
                      ></el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-tooltip  class="item" effect="dark" content="请输入标题" placement="top">
                    <el-form-item label-width="110px" label="标题：" class="postInfo-container-item" prop="title">
                      <el-input style="min-width:680px" placeholder="请输入标题" maxlength="100" v-model="postForm.title">
                        <template slot="append">您还可以输入{{ words - postForm.title.length }} 字</template>
                      </el-input>
                    </el-form-item>
                  </el-tooltip>
                </el-col>
                <!-- <el-col :span="4">
                  <div style="margin-top:10px;font-size:14px;margin-left:10px">
                    <span>您还可以输入{{ words - postForm.title.length }}个字</span>
                  </div>
                </el-col> -->
              </el-row>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="110px" label="设置标签：" class="postInfo-container-item" prop="nickname">
              <multiselect style="line-height:initial" v-model="postForm.labelsVal" :options="labels" @search-change="getLabelOptions" placeholder="搜索标签" selectLabel="选择" :multiple="true" deselectLabel="删除" track-by="id" :internalSearch="false" label="name">
                <span slot='noResult'>无搜索结果</span>
              </multiselect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="110px" label="上传封面：" class="postInfo-container-item">
              <el-upload
                class="upload-demo"
                :headers="headers"
                drag
                action="/tools/oss/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleUploadSuccess"
                list-type="picture"
                :file-list="fileList"
                :limit="2"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="editor-container">
              <!-- <el-tooltip  class="item" effect="dark" content="请输入内容" placement="top"> -->
                <el-form-item label-width="110px" label="资讯内容：" class="postInfo-container-item" prop="content">
                <Tinymce :height=400 ref="editor" v-model="postForm.content"  :value="postForm.content"/>
                </el-form-item>
              <!-- </el-tooltip> -->
            </div>
          </el-col>
        </el-row>

      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce';
import Upload from '@/components/Upload/headImage';
import MDinput from '@/components/MDinput';
import Sticky from '@/components/Sticky'; // 粘性header组件
import Multiselect from 'vue-multiselect'; // 使用的一个多选框组件，element-ui的select不能满足所有需求
import 'vue-multiselect/dist/vue-multiselect.min.css'; // 多选框组件css
import { validateURL } from '@/utils/validate';
import {  add,getSectionCascade, getInfoLabels } from '@/api/advisory';
import { getToken } from '@/utils/auth' // 验权

export default {
  name: 'add',
  components: { Tinymce, MDinput, Upload, Sticky, Multiselect },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: this.i18n[rule.field] + '为必填项',
          type: 'error',
          duration: 1000
        });
        callback(new Error(this.i18n[rule.field] + '为必填项'));
      } else {
        callback();
      }
    };
    const validateArrRequire = (rule, value, callback) => {
      if (value.length === 0) {
        this.$message({
          message: this.i18n[rule.field] + '为必填项',
          type: 'error'
        });
        callback(new Error(this.i18n[rule.field] + '为必填项'));
      } else {
        callback();
      }
    };
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validateURL(value)) {
          callback();
        } else {
          this.$message({
            message: 'url填写不正确',
            type: 'error'
          });
          callback(new Error(this.i18n[rule.field] + '为必填项'));
        }
      } else {
        this.$message({
          message: this.i18n[rule.field] + '为必填项',
          type: 'error'
        });
        callback(new Error(this.i18n[rule.field] + '为必填项'));
      }
    };
    return {
      labels:[],
      sections:[],
      sectionIds:[],
      headers:{},
      fileList:[],
      tagValue:'',
      words:100,
      authorId : this.$store.state.user.agencyId,
      postForm: {
        id:null,
        title:'',
        content:'',
        cover:'',
        labelsVal:[],
        // likeCount:10,
        // view:10,
        // weight:100,
        createTime : new Date().getTime(),
      },
      loading: false,
      i18n: {
        title: '标题'
      },
      rules: {
        title: [{ validator: validateRequire }]
      }
    };
  },
  mounted() {
    this.headers = {accessToken:getToken()}
    this.getSectionCascade()
    this.getLabelOptions('')
  },
  methods: {    
    getLabelOptions(title){
      getInfoLabels({labelName:title}).then(response => {
        const { code, data } = response
        if (code == 0) {
          this.labels = data;
        }
      })
    },
    getSectionCascade() {
      getSectionCascade().then(response => {
        const { code, data } = response
        if (code == 0) {
          this.sections = data;
          this.sectionIds = [data[0]['value']]
        }
      })
    },
    handleUploadSuccess(rst, file, fileList) {
      const { code, data: { picUrlList } } = rst
      const { postForm } = this
      if (code == 0) {
        postForm['cover'] = picUrlList[0]
        this.postForm = postForm
        this.fileList = [{ name: file.url, url: file.url }]
      }
    },    
    handlePreview(file) {
    },
    handleRemove(file, fileList) {
      this.postForm['cover'] = '';
    },
    // handleClose(tag) {
    //   this.postForm.labels.splice(this.postForm.labels.indexOf(tag), 1);
    // },
    handleFilter() {
      const { tagValue , postForm:{ labels } } = this;
      if(tagValue.trim().length==0){return}
      if(labels.some(e=>e==tagValue)){
        this.$message({
          message: '不能添加相同的标签',
          type: 'error'
        });
        return;
      }

      this.postForm.labels.push(tagValue);
      this.tagValue = '';
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true;
          let params = this.postForm;
          params['authorId'] = this.authorId
          const { content, cover, labelsVal } = params;
          const { sectionIds } = this;
          if(content.trim().length == 0 || content == '<p><br data-mce-bogus="1"></p>' || content  == '<p>&nbsp;</p>' || content == '<p><br></p>'){
              this.$message({
                message: '内容不能为空',
                type: 'error',
                duration: 1000
              });
              this.loading = false;
              return;
          }
          if(cover.length == 0){
              this.$message({
                message: '请上传封面',
                type: 'error',
                duration: 1000
              });
              this.loading = false;
              return;
          }
          if(sectionIds.length>0){
            params['sectionId'] = sectionIds[sectionIds.length-1]
          }
          if(labelsVal.length > 0){
            let labels = []
            labelsVal.map(e=>labels.push(e.id))
            params['labels'] = labels
          }
          delete params.labelsVal
          add(params).then(response => {
            const { code } = response
            if (code == 0) {
              this.$notify({
                title: '成功',
                message: '资讯发布成功',
                type: 'success',
                duration: 1000
              });
              this.loading = false;
              this.$router.push({ path: '/advisory/list' })
            }
          }).catch(() => {
              this.loading = false;
          })
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import 'src/styles/mixin.scss';
.upload-img-dev{
  width:320px;
  height:160px;
  position: absolute;
  right: 200px;
  bottom: 60px;
  z-index: 3;
}
.upload-img{
  width:320px;
  height:160px;
}
.tagLeft{
  margin-left:10px;
}
.title-prompt {
  position: absolute;
  right: 0px;
  font-size: 12px;
  top: 10px;
  color: #ff4949;
}
.createPost-container {
  position: relative;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;
    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;
      .postInfo-container-item {
        float: left;
      }
    }
    .editor-container {
      min-height: 500px;
      .editor-upload-btn-container {
        text-align: right;
        margin-right: 10px;
        .editor-upload-btn {
          display: inline-block;
        }
      }
    }
  }
  .word-counter {
    width: 40px;
    position: absolute;
    right: -10px;
    top: 0px;
  }
}
</style>
